#include "file.h"

const int DEFAULT_NUMBER_SEQUENCE[DEFAULT_QUANT_NUMBERS] = {9, 8, 7, 6, 5, 0, 4, 3, 2, 1, 3};

void print_array(const int* array, const int length) {
  register int t;
  for (t=0; t<length; ++t) printf("%d ", array[t]);
  printf("\n\n");
}

int get_stream_from_file(const char* file_name, int** unordered_array) {
  
  FILE *fp;
   
  if((fp = fopen(file_name, "r")) == NULL) {
    printf("File %s cannot be opened.\n", file_name);
    exit(1);
  }
  
  // Reading the first line which contains the size of the array
  char content[MAX_BUFFER];
  int array_length = 0;
  
  if (fgets(content, MAX_BUFFER, fp) != NULL) {
    array_length = atoi(content);
  }
  else {
    printf("There is no count number in the first line of file\n");
    exit(1);
  }
  
  // Filling unordered array with the file numbers
  *unordered_array = malloc(array_length * sizeof(int));
  int* temp_unordered_array = *unordered_array;
    
  while (fgets(content, MAX_BUFFER, fp) != NULL) {
                    
    char *token = strtok(content, " ");
    
    while (token != NULL) {
      *temp_unordered_array = atoi(token);
      temp_unordered_array++;
      token = strtok(NULL, " ");
    }
  }
  
  fclose(fp);  
  
  return array_length;
}


void load_default_file_values(const char* file_name) {
  
  register int count = 0;
  FILE *fp;
   
  if((fp = fopen(file_name, "w+")) == NULL) {
    printf("File %s cannot be opened.\n", file_name);
    exit(1);
  }
  
  fprintf(fp, "%d%s", DEFAULT_QUANT_NUMBERS, "\n");
  
  for (; count < DEFAULT_QUANT_NUMBERS;) {
    fprintf(fp, "%d ", DEFAULT_NUMBER_SEQUENCE[count++]);  
  }
  
  fclose(fp);
}



void load_random_file_values(const char* file_name, const int quant_numbers) {
  
  register int count = 1;
  FILE *fp;
   
  if((fp = fopen(file_name, "w+")) == NULL) {
    printf("File %s cannot be opened.\n", file_name);
    exit(1);
  }
  
  fprintf(fp, "%d%s", quant_numbers, "\n");
  
  srand(time(NULL));
  
  for (; count <= quant_numbers; count++) {
    fprintf(fp, "%d ", rand() % MAX_RAND);  
    if (count % NUMBERS_PER_LINE == 0) fprintf(fp, "%s ", "\n");
  }
  
  fclose(fp);
}
